package com.identify.identifydrawings;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.ObjectKey;
import com.google.gson.Gson;
import com.identify.identifydrawings.netUtils.JsonUtils;
import com.identify.identifydrawings.netUtils.Url;
import com.jhuster.imagecropper.CropIntent;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ManualCutting extends AppCompatActivity {
    ImageView img;
    //ImageView imgSearch;
    Button bt_cut;
    EditText tvCode;
    PhotoView photoView;
    File f;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manual_cutting);
        img = findViewById(R.id.img);
        // imgSearch  = findViewById(R.id.imgSearch);
        tvCode = findViewById(R.id.tvCode);
        bt_cut=findViewById(R.id.photocut);
        //tvCode1 = findViewById(R.id.tvCode1);
        photoView = (PhotoView) findViewById(R.id.imgSearch);
        // 启用图片缩放功能
        photoView.enable();
        Album.initialize(AlbumConfig.newBuilder(this)
                .setAlbumLoader(new MediaLoader())
                .build());
        initOcr();
    }
    private boolean hasGotToken;//是否設置orc成功

    /**
     * 初始化 orc
     */
    private void initOcr() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
                Log.e("TAG  AK，SK方式获取token成功", "token=" + token);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Log.e("TAG  AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(), "4p2Xng7gIhFRU9nhUGjZWd2p", "w31GOoyvs5ArTp2VTsEseBfqpGspllKy");
    }
//裁剪按钮

    // });

    //拍照
    public void takePhoto(View view) {
        Album.camera(this)
                .image()

                .onResult(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        startCropImage(result);
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                    }
                })
                .start();
    }

    /**
     * 相册选择图片
     */
    public void choosePhoto(View view) {
        Album.image(this)
                .singleChoice()
                .columnCount(2)
                .camera(false)
                .widget(
                        Widget.newDarkBuilder(this)
                                .title("选择图片")
                                .statusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                                .toolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        if (result == null || result.size() == 0) {
                            return;
                        }
                        startCropImage(result.get(0).getPath());
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                    }
                })
                .start();
    }

    File corpFile;

    //1. Using the CropIntent to help build the start intent
    private void startCropImage(String path) {
        Log.e("TAG", "startCropImagepath=" + path);
        // Create a CropIntent
        CropIntent intent = new CropIntent();

        // Set the source image filepath/URL and output filepath/URL (Optional)
        intent.setImagePath(path);
        String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaaaa";
        final File file = new File(dirName);
        if (!file.exists()) {
            file.mkdir();
        }

        corpFile = new File(dirName + "/" + "corp.png");
        intent.setOutputPath(corpFile.getAbsolutePath());

        // Set a fixed crop window size (Optional)
        //intent.setOutputSize(640,480);

        // set the max crop window size (Optional)
        //intent.setMaxOutputSize(800,600);

        // Set a fixed crop window's width/height aspect (Optional)
        //intent.setAspect(3,2);

        // start ImageCropper activity with certain request code and listen for result
        startActivityForResult(intent.getIntent(this), 0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == 0) {
            Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
            if (croppedUri == null) {
                return;
            }
            InputStream in = null;
            try {
                in = getContentResolver().openInputStream(croppedUri);
                Bitmap b = BitmapFactory.decodeStream(in);
                updateImg(b);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 回显图片，识别成果以及是否修改
     *
     * @param path
     */
    private void updateImg(Bitmap path) {
//        Glide.with(this)
//                .load(path)
//                .into(img);

        img.setImageBitmap(path);
        vertify(corpFile.getAbsolutePath());

        //刚才file1 是一个方法的局部变量 在外层是访问不到的
        //set  是设置 get是获取
        //logcat是打印日志
    }
    private String TAG = "TAG";


    //识别算法
    public void vertify(String path) {
        //操作
        final StringBuilder resultStr = new StringBuilder();
        RecognizeService.recAccurateBasic(this, path,
                new RecognizeService.ServiceListener() {
                    @Override
                    public void onResult(String result) {
                        Log.e("TAG", "recAccurateBasic  result=" + result);
                        VertifyData vertifyData = JsonUtils.parseJsonToBean(result, VertifyData.class);
                        Log.e("TAG", "recAccurateBasic  vertifyData=" + vertifyData);
                        if (vertifyData == null || vertifyData.getWords_result() == null || vertifyData.getWords_result().size() <= 0) {
                            setVertifyResult(resultStr.toString());
                        } else {
                            for (int i = 0; i < vertifyData.getWords_result().size(); i++) {
                                resultStr.append(vertifyData.getWords_result().get(i).getWords());
                            }
                            resultStr.append(".png");
                            setVertifyResult(resultStr.toString());
                        }
                    }
                });
//        return "12L104(三)-316.png";
    }

    private void setVertifyResult(String vertify) {
        if (TextUtils.isEmpty(vertify)) {
            Log.e("TAG", "识别失败");
            tvCode.setText("识别失败,请手动输入");
        } else {
            Log.e("TAG", "识别成功=" + vertify);
            tvCode.setText(vertify);
        }
    }

    //搜索
    public void searchImg(View view) {
        //oss
        //返回图片
        //imgSearch
        String text = tvCode.getText().toString();
        getImage(text);
    }

    //獲取token
    private String getImage(String e_account) {
        String results = null;
        HashMap map = new HashMap();
        //?Action=AssumeRole&&RoleArn=acs:ram::1843770436407740:role/AliyunOSSTokenGeneratorRole&RoleSessionName=banyaolian
        map.put("e_account", e_account);

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url(Url.getFileFormNet + "?e_account=" + e_account)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG", "onFailure: " + e.getMessage());
                ;

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //  String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LungFile";
                Log.e("TAG", "response=" + response);

                int code = response.code();
                if (code != 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ManualCutting.this, "key值不对", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaaaa";

                final File file = new File(dirName);
                if (!file.exists()) {
                    file.mkdir();
                }

                File file1 = new File(dirName + "/" + "facenew1.png");
                if (response != null) {
                    InputStream is = response.body().byteStream();
                    FileOutputStream fos = new FileOutputStream(file1);
                    int len = 0;
                    byte[] buffer = new byte[2048];
                    while (-1 != (len = is.read(buffer))) {
                        fos.write(buffer, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                }
                setImg(file1);
            }
        });
        return results;
    }

    /**
     * 加载图片
     *
     * @param file
     */
    private void setImg(final File file) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Glide.with(ManualCutting.this)
                        .load(file.getAbsolutePath())
                        .into(photoView);
            }
        });
        // 获取图片信息
        //  Info info = photoView.getInfo();
// 从普通的ImageView中获取Info
        //Info info = PhotoView.getImageViewInfo(ImageView);
// 从一张图片信息变化到现在的图片，用于图片点击后放大浏览，具体使用可以参照demo的使用
        //photoView.animaFrom(info);
// 从现在的图片变化到所给定的图片信息，用于图片放大后点击缩小到原来的位置，具体使用可以参照demo的使用
//        photoView.animaTo(info,new Runnable() {
//            @Override
//            public void run() {
//                //动画完成监听
//            }
//        });
// 获取/设置 动画持续时间
        //photoView.setAnimaDuring(1000);
        int d = photoView.getAnimaDuring();
// 获取/设置 最大缩放倍数
        // photoView.setMaxScale(2);
        //  float maxScale = photoView.getMaxScale();
// 设置动画的插入器
        // photoView.setInterpolator(Interpolator interpolator);


    }
}
